<template>
	<scroll-view class="scroll-area" scroll-y>
		<view class="container">
			<text class="chart-cont-title">{{getTitle()}}</text>

			<view class="chart-cont-time-tab">
				<view :class="[timeActive == index ? 'chart-cont-time-tab-active' : 'chart-cont-time-tab-item']"
					v-for="(item, index) in timeList" :key="index" @click="timeActive = index">
					{{item.name}}
				</view>
			</view>

			<view :style="{marginTop: '25rpx'}">
				<zxz-uni-datetime-picker :type="timeType" :clear-icon="false" v-model="timeModel" @change="change" />
			</view>

			<l-echart ref="chartRef"></l-echart>
		</view>
	</scroll-view>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted, defineProps, getCurrentInstance, watch } from 'vue';
	import * as energy from "@/api/energy.ts";

	const { proxy } = getCurrentInstance();

	const props = defineProps<{
		keys : string | undefined;
		projectId : number | undefined;
	}>()

	const getTitle = () => {
		switch (props.keys) {
			case energy.GartherType.xmznh:
				option.legend.data = ['能耗'];
				option.series[0].name = '能耗';
				option.series[0].tooltip = {
					valueFormatter: function (value) {
						return `${value}kw.h`;
					},
				}
				return "能耗趋势";
			case energy.GartherType.dwpfmdf:
				option.legend.data = ['电费'];
				option.series[0].name = '电费';
				option.series[0].tooltip = {
					valueFormatter: function (value) {
						return `${value}元`;
					},
				}
				return "电费趋势";
			default:
				return "趋势"
		}
	}

	const change = (e) => {
		console.log("选择了时间", e)
		switch (timeActive.value) {
			case 0:
				startTime.value = e
				endTime.value = e
				break;
			case 1:
				startTime.value = e[0]
				endTime.value = e[1]
				break;
			case 2:
				startTime.value = e[0]
				endTime.value = e[1]
				break;
			case 3:
				startTime.value = `${e}-01`
				endTime.value = `${e}-12`
				break;
		}
		getChartInfo();
	}


	const timeType = ref("date")
	const timeModel = ref([proxy.dayjs().format('YYYY-MM-DD'), proxy.dayjs().format('YYYY-MM-DD')])
	const timeActive = ref(0)
	const timeList = ref([{ name: '小时', value: 0 }, { name: '日报', value: 1 }, { name: '月报', value: 2 }, { name: '年报', value: 3 }])

	const startTime = ref(proxy.dayjs().format('YYYY-MM-DD'));
	const endTime = ref(proxy.dayjs().format('YYYY-MM-DD'));

	// 监听时间筛选
	watch(timeActive, (newValue, oldValue) => {
		console.log(`timeActive 从 ${oldValue} 变为 ${newValue}`);
		switch (newValue) {
			case 0:
				startTime.value = proxy.dayjs().format('YYYY-MM-DD')
				endTime.value = proxy.dayjs().format('YYYY-MM-DD')
				timeType.value = "date";
				timeModel.value = proxy.dayjs().format('YYYY-MM-DD');
				break;
			case 1:
				startTime.value = proxy.dayjs().subtract(7, 'day').format('YYYY-MM-DD')
				endTime.value = proxy.dayjs().format('YYYY-MM-DD')
				timeType.value = "daterange";
				timeModel.value = [startTime.value, endTime.value];
				break;
			case 2:
				startTime.value = proxy.dayjs().subtract(30, 'day').format('YYYY-MM-DD')
				endTime.value = proxy.dayjs().format('YYYY-MM-DD')
				timeType.value = "yearMonthRange";
				timeModel.value = [startTime.value, endTime.value];
				break;
			case 3:
				startTime.value = proxy.dayjs().subtract(12, 'month').format('YYYY-MM')
				endTime.value = proxy.dayjs().format('YYYY-MM')
				timeType.value = "year";
				timeModel.value = proxy.dayjs().format('YYYY');
				break;
		}
		getChartInfo();
	});

	const echarts = require('../../uni_modules/lime-echart/static/echarts.min');
	const chartRef = ref(null);
	const myChart = ref(null);
	const xData = ref([]);
	const yBarData = ref([]);
	const option = reactive({
		graphic: {
			type: 'text',
			left: 'center',
			top: 'middle',
			invisible: yBarData.value.length > 0, // 有数据时隐藏提示
			style: {
				text: '暂无数据',
				fontSize: 16,
				fill: '#999'
			}
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				//阴影指示器
				type: 'shadow'
			},
			confine: true
		},
		legend: {
			top: 10,
			left: "center",
			itemWidth: 10,
			itemHeight: 5,
			data: ['耗电'],
		},
		grid: {
			top: 40,
			left: 10,
			right: 10,
			bottom: 20,
			containLabel: true,
		},
		xAxis: [
			{
				type: 'category',
				data: xData.value,
			}
		],
		yAxis: [
			{
				// 数值轴，适用于连续数据。
				type: 'value',
			}

		],
		series: [
			{
				name: '耗电',
				type: 'bar',
				barWidth: 10,
				tooltip: {
					valueFormatter: function (value) {
						return value;
					},
				},
				itemStyle: {
					color: "#BCCAFA",
					borderColor: "#5F83F9",
					borderWidth: 1,
				},
				data: yBarData.value,
			},
		]
	});

	onMounted(() => {
		getChartInfo()
	})

	const getChartInfo = async () => {

		if (props.projectId === undefined) {
			return;
		}

		var format = energy.FormatType.day;
		var key = props.keys;
		switch (timeActive.value) {
			case 0:
				//按小时统计
				if (props.keys == energy.GartherType.xmznh) {
					//能耗
					key = `H`
				} else if (props.keys == energy.GartherType.dwpfmdf) {
					//电费
					key = `M`
				}
				format = undefined;
				break;
			case 1:
				format = energy.FormatType.day;
				break
			case 2:
				format = energy.FormatType.day;
				break;
			case 3:
				format = energy.FormatType.month;
				break
		}


		const dataResult = await energy.getDataByTUOKs({
			"isLike": true,
			"startTime": startTime.value, "endTime": endTime.value,
			"format": format, "oper": energy.OperType.coun, "keys": `0_0_${props.projectId}_${key}`
		})


		xData.value.length = 0;
		yBarData.value.length = 0;
		console.log(`0_0_${props.projectId}_${key}`);
		if (dataResult[`0_0_${props.projectId}_${key}`] != null && dataResult[`0_0_${props.projectId}_${key}`].length > 0) {
			dataResult[`0_0_${props.projectId}_${key}`].forEach(item => {
				if (timeActive.value == 0) {
					xData.value.push(`${item.time} ${item.key.slice(1)}时`);
				} else {
					xData.value.push(item.time);
				}
				yBarData.value.push(item.value);
			})
		}

		if(yBarData.value.length>0){
			option.graphic.invisible= true;
		}else{
			option.graphic.invisible= false;
		}
		initChart();
	}

	const initChart = async () => {
		if (!chartRef.value) return
		const chart = await chartRef.value.init(echarts)
		chart.setOption(option)
		myChart.value = chart
	}

	defineExpose({
		getChartInfo
	})
</script>

<style lang="scss" scoped>
	.scroll-area {
		// height: 100%;
	}

	.container {
		display: flex;
		flex-direction: column;
		// padding: 25rpx;

		.chart-cont-title {
			font-size: 28rpx;
			color: #333;
			font-weight: 600;
		}

		.chart-cont-time-tab {
			margin-top: 30rpx;
			display: flex;

			.chart-cont-time-tab-item,
			.chart-cont-time-tab-active {
				margin-left: 30rpx;
				height: 60rpx;
				line-height: 60rpx;
				flex: 1;
				color: #5A6570;
				font-size: 22rpx;
				text-align: center;
				border-radius: 5rpx;
				border: 1px solid #ccc;
				background-color: #fff;

				&:first-child {
					margin-left: 0;
				}
			}

			.chart-cont-time-tab-active {
				color: #5F83F9;
				border-color: #5F83F9;
				background-color: rgba(95, 131, 249, 0.1);
			}
		}
	}
</style>